package com.smasher.nfc.util

import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import androidx.annotation.RequiresPermission


class VibrationHelper(context: Context) {

    private val vibrator: Vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        val vibratorManager =
            context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
        vibratorManager.defaultVibrator
    } else {
        context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    }

    private fun hasVibrator(): Boolean {
        return vibrator.hasVibrator()
    }


    @RequiresPermission(android.Manifest.permission.VIBRATE)
    fun doVibration(repeat: Int = -1) {
        if (hasVibrator()) {
            // 创建一个震动模式：0为停顿时间，100为震动时间（毫秒）
            val pattern = longArrayOf(0, 100, 200, 300)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                // For API 26 and above
                val vibrationEffect = VibrationEffect.createWaveform(pattern, repeat)
                vibrator.vibrate(vibrationEffect)
            } else {
                // For devices running API 25 and below
                // 设置震动模式，并开启震动，最后第二个参数表示重复次数-1表示无限循环直到取消
                @Suppress("DEPRECATION")
                vibrator.vibrate(pattern, repeat)
            }
        }
    }

    @RequiresPermission(android.Manifest.permission.VIBRATE)
    fun cancelVibration() {
        vibrator.cancel()
    }

}